<script>
import * as maptalks from "maptalks";
import "maptalks/dist/maptalks.css";
import { ElMessage } from "element-plus";
let map;
export default {
  name: "CoolChess",
  mounted() {
    this.initMap();
    this.initChessboard();
  },
  data() {
    return {
      tom: "玩家一 执黑",
      jerry: "玩家二 执白",
      rowsCount: 3,
      columnsCount: 3,
      chessFlag: 0,
      chessRecords: [],
      switchEnable: false,
      bigStep: 0, //同一步落的两子显示一样的数字
    };
  },
  methods: {
    initMap() {
      map = new maptalks.Map("map", {
        center: [0, 0],
        zoom: 14,
        baseLayer: new maptalks.ImageLayer("images", [
          {
            url: "./world.png",
            extent: [-18, -18, 18, 18],
            opacity: 1,
          },
        ]),
      });
    },
    /**
     * 初始化棋盘
     */
    initChessboard() {
      const chessboardLayer = new maptalks.VectorLayer("chessboard").addTo(map);
      const chessboardobserveLayer = new maptalks.VectorLayer(
        "chessboardobserve"
      ).addTo(map);
      const chessLayer = new maptalks.VectorLayer("chess").addTo(map);

      for (let i = 0; i < this.columnsCount - 1; i++) {
        for (let j = 0; j < this.rowsCount - 1; j++) {
          const cbPolygon = new maptalks.Polygon(
            [
              [
                [i, j],
                [i, j + 1],
                [i + 1, j + 1],
                [i + 1, j],
                [i, j],
              ],
            ],
            {
              visible: true,
              editable: true,
              cursor: "pointer",
              shadowBlur: 0,
              shadowColor: "black",
              draggable: false,
              dragShadow: false, // display a shadow during dragging
              drawOnAxis: null, // force dragging stick on a axis, can be: x, y
              symbol: {
                lineColor: "#34495e",
                lineWidth: 2,
                polygonFill: "rgb(135,196,240)",
                polygonOpacity: 0.6,
              },
            }
          );
          cbPolygon.addTo(chessboardLayer);
        }
      }

      for (let i = -0.5; i < this.columnsCount - 1; i++) {
        for (let j = -0.5; j < this.rowsCount - 1; j++) {
          const cboPolygon = new maptalks.Polygon(
            [
              [
                [i, j],
                [i, j + 1],
                [i + 1, j + 1],
                [i + 1, j],
                [i, j],
              ],
            ],
            {
              id: `${i + 0.5}-${j + 0.5}`,
              visible: true,
              editable: true,
              cursor: "pointer",
              shadowBlur: 0,
              shadowColor: "black",
              draggable: false,
              dragShadow: false, // display a shadow during dragging
              drawOnAxis: null, // force dragging stick on a axis, can be: x, y
              symbol: {
                lineColor: "#34495e",
                lineWidth: 0,
                polygonFill: "rgba(135,0,0,0.01)",
                polygonOpacity: 0.6,
              },
            }
          );
          cboPolygon.on("click", () => {
            console.log(`${i + 0.5}-${j + 0.5}`, "==== cboPolygon.onclick");
            this.addStep(i + 0.5, j + 0.5, chessLayer);
          });
          cboPolygon.addTo(chessboardobserveLayer);
        }
        map.fitExtent(chessboardobserveLayer.getExtent());
      }
    },
    /**
     * 落子
     */
    addStep(x, y, chessLayer) {
      // 重复点位不能落子
      let checkResult = true;
      this.chessRecords.forEach((item) => {
        if (item.position[0] === x && item.position[1] === y) {
          checkResult = false;
          ElMessage("此处不能再落子了！");
          return;
        }
      });
      if (checkResult && this.switchEnable) {
        // 第二子需要和第一子相邻
        const [x0, y0] =
          this.chessRecords[this.chessRecords.length - 1].position;
        if (Math.abs(x0 - x) + Math.abs(y0 - y) > 1) {
          checkResult = false;
          ElMessage("第二子需要和第一子相邻！");
          return;
        }
      }
      if (checkResult) {
        var marker = new maptalks.Marker([x, y], {
          symbol: {
            markerFile:
              this.chessFlag === 1
                ? "./assets/white.svg"
                : "./assets/black.svg",
            markerWidth: 100,
            markerHeight: 100,
            // markerDx: 20,
            markerDy: 50,
            textName: this.bigStep,
            textFill: "#fff",
            textHaloFill: "#000",
            textHaloRadius: 1,
          },
        });
        marker.addTo(chessLayer);

        const stepid = `${this.chessRecords.length}`;
        const player = `${this.chessFlag === 0 ? this.tom : this.jerry}`;
        this.chessRecords.push({ stepid, player, position: [x, y] });
        if (this.chessRecords.length === this.columnsCount * this.rowsCount) {
          const winner = `${this.chessFlag === 1 ? this.tom : this.jerry}`;
          ElMessage(`游戏结束！${winner}获胜！}`);
        }
        this.switchEnable = this.isSingleStep();
      }
    },
    /**
     * 判断是否是单步落子
     */
    isSingleStep() {
      if (this.chessRecords.length > 0) {
        if (this.chessRecords.length === 1) {
          return this.chessFlag === 0;
        } else {
          const playerPast =
            this.chessRecords[this.chessRecords.length - 2].player;
          const playerCurr =
            this.chessRecords[this.chessRecords.length - 1].player;
          if (playerCurr !== playerPast) {
            if (
              (this.chessFlag === 0 && playerCurr === this.tom) ||
              (this.chessFlag === 1 && playerCurr === this.jerry)
            ) {
              return true;
            } else {
              return false;
            }
          } else {
            this.chessFlag = this.chessFlag === 0 ? 1 : 0;
            this.bigStep++;
            return false;
          }
        }
      } else {
        return false;
      }
    },
    onSwitchClick() {
      this.chessFlag = this.chessFlag === 0 ? 1 : 0;
      this.switchEnable = this.isSingleStep();
      this.bigStep++;
    },
    /**
     * 需要修改棋盘时重置
     */
    onBoardChanged() {
      this.chessFlag = 0;
      this.switchEnable = false;
      this.chessRecords.length = 0;
      map.removeLayer(["chessboard", "chessboardobserve", "chess"]);
      this.initChessboard();
      this.bigStep = 0;
    },
  },
};
</script>

<template>
  <div class="leftside">
    <el-button type="primary" :disabled="!switchEnable" @click="onSwitchClick"
      >我下好了</el-button
    >
    <div class="player1">
      <el-card style="height: 100%">
        <template #header>{{ tom }}</template>
        <img src="./assets/avatar.png" style="width: 20%" />
      </el-card>
    </div>
    <div class="chessrecords">
      <el-table :data="chessRecords" style="width: 100%">
        <el-table-column prop="stepid" label="stepid" width="80" />
        <el-table-column prop="player" label="player" width="80" />
        <el-table-column prop="position" label="position" />
      </el-table>
    </div>
    <div class="player1">
      <el-card style="height: 100%">
        <template #header>{{ jerry }}</template>
        <img src="./assets/avatar.png" style="width: 20%" />
      </el-card>
    </div>
    <div class="customboard">
      <el-input-number
        v-model="columnsCount"
        size="small"
        @change="onBoardChanged"
      />列
      <el-input-number
        v-model="rowsCount"
        size="small"
        @change="onBoardChanged"
      />行
    </div>
  </div>
  <div id="map" class="container"></div>
</template>

<style scoped></style>
